//加载文档的时候检查是否登录
document.addEventListener("DOMContentLoaded", () => {
    // 初始化加载个人信息
    const userID = sessionStorage.getItem('userID');
    if (userID) {
        fetchPersonalInfo(userID);
    } else {
        console.error("用户未登录！");
    }
    // 默认加载课程列表
    showSection('course-list');
    fetchCourseList();

    // 保存个人信息按钮事件绑定
    const saveButton = document.querySelector('#personal-info .btn');
    saveButton.addEventListener('click', savePersonalInfo);
});
//侧边导航栏
function showSection(sectionId) {
    // 隐藏所有内容区
    document.querySelectorAll('.content-section').forEach(section => {
        section.classList.add('hidden');
    });
    // 显示选定的内容区
    document.getElementById(sectionId).classList.remove('hidden');

    const userID = sessionStorage.getItem('userID');
    if (!userID) {
        console.error("用户未登录！");
        return;
    }

    if (sectionId === 'personal-info') {
        fetchPersonalInfo(userID);
    } else if (sectionId === 'course-list') {
        fetchCourseList();
    } else if (sectionId === 'enrollment') {
        fetchEnrollmentData(userID);
    }
}
//加载个人信息
function fetchPersonalInfo(userID) {
    fetch(`http://localhost:8080/api/user/${userID}`)
        .then(response => response.json())
        .then(data => {
            document.getElementById('id').value = data.id || '';
            document.getElementById('username').value = data.username || '';
            document.getElementById('password').value = data.password ||'';
        })
        .catch(error => console.error('加载个人信息失败:', error));
}
//保存修改个人信息
function savePersonalInfo(event) {
    event.preventDefault(); // 阻止默认表单提交行为

    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const userID = sessionStorage.getItem('userID'); // 从 sessionStorage 获取用户 ID

    if (!userID) {
        alert("用户未登录，请重新登录！");
        return;
    }

    // 校验输入
    if (!nickname.trim() || !password.trim()) {
        alert("昵称和密码不能为空！");
        return;
    }

    // 构造请求数据
    const payload = {
        id: userID,
        username: username,
        password: password
    };

    // 向后端发送更新请求
    fetch('http://localhost:8080/api/updateUserInfo', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error("更新失败，请稍后再试！");
        }
        return response.json();
    })
    .then(data => {
        alert(data.message || "个人信息更新成功！");
    })
    .catch(error => {
        console.error("保存个人信息时出错:", error);
        alert("保存个人信息失败，请检查网络连接！");
    });
}

let allCourses = []; // 存储所有课程数据

// 获取课程列表数据
function fetchCourseList() {
    fetch('http://localhost:8080/api/getCourses')
        .then(response => response.json())
        .then(data => {
            allCourses = data.courses; 
            renderCourses(allCourses);
        })
        .catch(error => console.error("获取课程列表失败:", error));
}

// 筛选课程
function filterCourses(event) {
    event.preventDefault(); // 阻止表单默认行为

    const searchInput = document.querySelector('.search-input').value.trim().toLowerCase();
    if (!searchInput) {
        renderCourses(allCourses); // 输入为空时显示所有课程
        return;
    }

    const filteredCourses = allCourses.filter(course =>
        course.name.toLowerCase().includes(searchInput)
    );
    renderCourses(filteredCourses);
}

// 渲染课程列表
function renderCourses(courses) {
    const container = document.getElementById('course-container');
    container.innerHTML = ''; // 清空之前的内容

    if (courses.length === 0) {
        container.innerHTML = '<p>未找到符合条件的课程。</p>';
        return;
    }

    courses.forEach(course => {
        const courseCard = document.createElement('div');
        courseCard.className = 'course-card';

        courseCard.innerHTML = `
            <h2>${course.name}</h2>
            <p><strong>时间：</strong>${course.time}</p>
            <p><strong>地点：</strong>${course.location}</p>
            <p><strong>讲师：</strong>${course.instructor}</p>
            <a href="#" class="btn" onclick="enrollCourse('${course.id}')">报名</a>
        `;

        container.appendChild(courseCard);
    });
}

// 报名课程
function enrollCourse(courseId) {
    const userID = sessionStorage.getItem('userID');
    if (!userID) {
        alert("请先登录！");
        return;
    }

    fetch('http://localhost:8080/api/enrollCourse', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userID, courseId })
    })
        .then(response => response.json())
        .then(data => {
            alert(data.message || "报名成功！");
            fetchCourseList(); // 重新加载课程列表
        })
        .catch(error => console.error("报名课程失败:", error));
}

// 获取我的报名信息
function fetchEnrollmentList() {
    const userID = sessionStorage.getItem('userID');
    if (!userID) {
        alert("请先登录！");
        return;
    }

    fetch(`http://localhost:8080/api/getEnrollments?userID=${userID}`)
        .then(response => response.json())
        .then(data => {
            renderEnrollments(data.enrollments); // 假设后端返回 { enrollments: [...] }
        })
        .catch(error => console.error("获取报名列表失败:", error));
}

// 渲染报名信息
function renderEnrollments(enrollments) {
    const container = document.getElementById('enrollment-container');
    container.innerHTML = ''; // 清空之前的内容

    if (enrollments.length === 0) {
        container.innerHTML = '<p>您尚未报名任何课程。</p>';
        return;
    }

    enrollments.forEach(enrollment => {
        const enrollmentItem = document.createElement('li');
        enrollmentItem.className = 'enrollment-item';

        const statusClass = getStatusClass(enrollment.status);

        enrollmentItem.innerHTML = `
            <h2>${enrollment.courseName}</h2>
            <p><strong>时间：</strong>${enrollment.startTime}</p>
            <p><strong>状态：</strong><span class="status ${statusClass}">${enrollment.status}</span></p>
            <a href="#" class="btn" onclick="cancelEnrollment('${enrollment.id}')">取消报名</a>
        `;

        container.appendChild(enrollmentItem);
    });
}

// 获取状态对应的类名
function getStatusClass(status) {
    switch (status) {
        case '进行中':
            return 'ongoing';
        case '已完成':
            return 'completed';
        case '已取消':
            return 'cancelled';
        default:
            return '';
    }
}

// 取消报名
function cancelEnrollment(enrollmentID) {
    const userID = sessionStorage.getItem('userID');
    if (!userID) {
        alert("请先登录！");
        return;
    }

    fetch('http://localhost:8080/api/cancelEnrollment', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userID, enrollmentID })
    })
        .then(response => response.json())
        .then(data => {
            alert(data.message || "取消报名成功！");
            fetchEnrollmentList(); // 重新加载报名列表
        })
        .catch(error => console.error("取消报名失败:", error));
}

// 点击导航栏“我的报名”时加载报名数据
document.querySelector('a[href="#"]').addEventListener('click', (event) => {
    if (event.target.innerText === "我的报名") {
        fetchEnrollmentList();
    }
});
